package main

import (
	"DpCenter/config"
	"DpCenter/controller"
	"DpCenter/datasource"
	"DpCenter/service"
	"github.com/gamelife1314/logging"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/kataras/iris/v12/sessions"
	client "github.com/xuanbo/eureka-client"
	"strconv"
	"time"
)
var logger = logging.GetDefaultLogger()
func main() {

	app := newApp()
	config := config.InitConfig()
	//注册静态资源
	app.HandleDir("/static", config.StaticPath)
	app.HandleDir("/manage/static", "./static")
	app.HandleDir("/img", "./static/img")

	//应用App设置
	configation(app,config)

	//注册到eureka
	register2Eureka(config)

	//路由设置
	mvcHandle(app)

	app.Run(
		iris.Addr("localhost:"+config.Port),                               //在端口8080进行监听
		iris.WithoutServerError(iris.ErrServerClosed), //无服务错误提示
		iris.WithOptimizations,                        //对json数据序列化更快的配置
	)
}

//注册到eureka
func register2Eureka(appConfig *config.AppConfig){
	    port, err := strconv.Atoi(appConfig.Port)
	    if err != nil{
			logger.Info("端口号必须为全数字")
		}
		// 1.创建客户端
		c := client.NewClient(&client.Config{
		DefaultZone: "http://admin:admin@192.168.217.139:8761/eureka/",
		App:         "DpCenter",
		Port:         port,
		})
		// 2.启动client，注册到server。并定心跳、刷新服务列表
		c.Start()
}

//构建App
func newApp() *iris.Application {
	app := iris.New()
	//注册视图文件
	app.RegisterView(iris.HTML("./static", ".html"))
	app.Get("/", func(context iris.Context) {
		context.View("index.html")
	})

	return app
}

/**
 * 项目设置
 */
func configation(app *iris.Application ,appConfig *config.AppConfig) {

	//配置 字符编码
	app.Configure(iris.WithConfiguration(iris.Configuration{
		Charset: "UTF-8",
	}))

	//设置日志级别，在config.json log_level 配置
	app.Logger().SetLevel(appConfig.LogLevel)
	//错误配置
	//未发现错误
	app.OnErrorCode(iris.StatusNotFound, func(context iris.Context) {
		context.JSON(iris.Map{
			"errmsg": iris.StatusNotFound,
			"msg":    " not found ",
			"data":   iris.Map{},
		})
	})

	app.OnErrorCode(iris.StatusInternalServerError, func(context iris.Context) {
		context.JSON(iris.Map{
			"errmsg": iris.StatusInternalServerError,
			"msg":    " interal error ",
			"data":   iris.Map{},
		})
	})
}

//MVC 架构模式处理
func mvcHandle(app *iris.Application) {
	//启用session
	sessManager := sessions.New(sessions.Config{
		Cookie:  "sessioncookie",
		Expires: 24 * time.Hour,
	})

	engine := datasource.NewMysqlEngine()

	//管理员模块功能
	adminService := service.NewAdminService(engine)

	admin := mvc.New(app.Party("/admin"))//设置路由组
	admin.Register(
		adminService,
		sessManager.Start,
	)
	//通过mvc的Handle方法进行控制器的指定
	admin.Handle(new(controller.AdminController))
}